package com.play.ballen.me.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.core.content.ContextCompat
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.config.KVConst
import com.play.ballen.databinding.ActivityRechargeBinding
import com.play.ballen.me.vm.RechargeVM
import com.tbruyelle.rxpermissions2.RxPermissions
import com.yuven.appframework.base.BaseStdTitleActivity
import com.yuven.appframework.network.RxSchedulerHelper
import com.yuven.appframework.util.ClipboardUtils
import com.yuven.appframework.util.FileUtil
import com.yuven.appframework.util.addToDisposable
import com.yuven.appframework.util.imageloader.ImageUtil
import com.yuven.appframework.util.setOnSingleClickListener
import com.yuven.baselib.utils.Logger
import com.yuven.baselib.utils.ResourceUtil
import com.yuven.baselib.utils.ViewUtils
import io.reactivex.Observable

class RechargeActivity : BaseStdTitleActivity<RechargeVM, ActivityRechargeBinding>() {

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, RechargeActivity::class.java)
            context.startActivity(starter)
        }
    }

    override fun viewModelClass(): Class<RechargeVM> {
        return RechargeVM::class.java
    }

    override fun contentLayoutId(): Int {
        return R.layout.activity_recharge
    }

    override fun initObserver() {
        super.initObserver()

        viewModel.rechargeInfo.observe(this) {
            it.run {
                dataBinding.tvAddress.text = address
                ImageUtil.instance.loadImage(0, 0, qrcode, dataBinding.imgQRCode)
                dataBinding.tvDesc.text = memo
            }
        }
    }

    private val onClickListener = tag@{ v: View ->
        if (viewModel.rechargeInfo.value == null) {
            return@tag
        }

        when (v.id) {
            R.id.tvSaveQRCode -> {
                RxPermissions(this).request(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                    .subscribe({ granted ->
                        if (granted) {
                            saveQrCode()
                        } else {
                            ToastUtils.show(ResourceUtil.getString(R.string.permission_denied))
                        }
                    }, { throwable ->
                        Logger.i("request permission error throws message:${throwable.message}")
                    }).addToDisposable(mCompositeDisposable)
            }

            R.id.btnCopyAddress -> {
                ClipboardUtils.setText(dataBinding.tvAddress.text.toString().trim(), this)
                ToastUtils.show(ResourceUtil.getString(R.string.me_copy))
            }
        }
    }

    override fun onToolbarRightIconClick() {
        MoneyLogActivity.start(
            this,
            ResourceUtil.getString(R.string.recharge_record_title),
            KVConst.MONEY_LOG_TYPE_RECHARGE,
            ""
        )
    }

    override fun initData() {
        viewModel.recharge()

        val rightIcon = getTitleBarLayout().getRightIcon()
        rightIcon?.visibility = View.VISIBLE
        rightIcon?.setImageResource(R.mipmap.ic_me_recharge_detail)

        dataBinding.tvSaveQRCode.setOnSingleClickListener(onClickListener)
        dataBinding.btnCopyAddress.setOnSingleClickListener(onClickListener)
    }

    override fun initIntent(intent: Intent?) {
    }

    override fun getToolBarTitle(): String = ResourceUtil.getString(R.string.recharge_title)

    private fun saveQrCode() {
        Observable.just(1)
            .map {
                val bitmapNew = ViewUtils.view2Bitmap(
                    dataBinding.imgQRCode,
                    ContextCompat.getColor(this, com.yuven.appframework.R.color.white)
                )
                FileUtil.saveBitmapToPictures(
                    this,
                    bitmapNew,
                    ResourceUtil.getString(R.string.recharge_qrcode_save_success)
                )
                it
            }
            .compose(RxSchedulerHelper.io_main())
            .subscribe({
                Logger.i("RechargeActivity save bitmap success")
            }, { throwable ->
                Logger.i("RechargeActivity save bitmap error,msg = ${throwable.message}")
            }).addToDisposable(mCompositeDisposable)
    }
}